
#include	"Animation.h"
#include	"Surface.h"

Animation::Animation(){
	numFrames = 0;
	fps = 30;
	currentFrame = 1;
	playing = false;
	frameTime = 0;
	framesCols = framesRows = 0;
	repeat = false;
}

bool Animation::init(char* framesImage, int frameWidth, int frameHeight, int fps){

	if( frameWidth <= 0 || frameHeight <= 0 || fps <= 0)
		return false;

	if(!Object::init(framesImage))
		return false;

	this->fps = fps;

	framesCols = objectSurface->w / frameWidth;
	framesRows  = objectSurface->h / frameHeight;

	numFrames = framesCols * framesRows;

	frameRect.x = 0;
	frameRect.y = 0;
	frameRect.w = frameWidth;
	frameRect.h = frameHeight;

	return true;
}

void Animation::loop(){

	if(!playing)
		return;

	Object::loop();

	if( SDL_GetTicks() >= frameTime )
		nextFrame();
}

void Animation::render(SDL_Surface* destSurface){
	Surface::OnDraw(destSurface, objectSurface, (int) x, (int) y, frameRect.x, frameRect.y, frameRect.w, frameRect.h);
}

void Animation::cleanup(){

	Object::cleanup();
}

void Animation::nextFrame(){
	
	if( currentFrame + 1 > numFrames )
	{
		if(repeat)
			rewind();
		else
			stop();
	}
	else
	{
		currentFrame++;

		int col = (currentFrame - 1) % framesCols;
		int lin = (currentFrame - 1) / framesCols;

		frameRect.x = col * frameRect.w;
		frameRect.y = lin * frameRect.h;

		frameTime = SDL_GetTicks() + 1000 / fps;
	}
}

void Animation::play(){
	
	if(playing)
		return;

	playing = true;
	frameTime = SDL_GetTicks() + 1000 / fps;
}

void Animation::stop(){
	playing = false;
}

void Animation::rewind(){
	currentFrame = 1;
	frameTime = SDL_GetTicks() + 1000 / fps;
}

